define(function(require, exports){
	var $ = require('jquery');
	var util = require('util');
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var popwin = require('@base/dialog').base;

	// 创建新条件 模块
	var AddCondition = popwin.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'labelUrl': 'campaign/labels'
				,'view_model': {
					'showDelBtn': false,
					'clickShowMenu': this.eventShowMenu, // 点击弹出相应菜单
					'silence': false,
					'clickAdd': this.eventAdd, // 增加一条
					'clickRemove': this.eventRemove, // 删除一条
					'conditions': [], // 条件数组
					'email': true,
					'syslog': true,
					// 添加条件弹窗的button的值
					'buttonValue': '',
					// 选择按钮点击事件
					'buttonClick': this.eventButtonClick
				}
				,operator: {
					'metric': [
						{Name: _T('大于'), _id: '$gt'},
						{Name: _T('等于'), _id: '$eq'},
						{Name: _T('小于'), _id: '$lt'}
					]
					,'dim': [
						{Name: _T('包含'), _id: '$in'},
						{Name: _T('排除'), _id: '$nin'}
					]
					,'newDim': [
						{Name: _T('包含'), _id: '$in'}
					]
				}
				,dim: [
					{'Name': LANG('选择指标'), '_id': 'metric'},
					{'Name': LANG('创意ID'), '_id': 'creative_id'},
					{'Name': LANG('活动ID'), '_id': 'campaign_id'},
					{'Name': LANG('创意包ID'), '_id': 'package_id'},
					{'Name': LANG('活动名称'), '_id': 'campaign_name'},
					{'Name': LANG('活动标签'), '_id': 'campaign_label'},
					{'Name': LANG('渠道'), '_id': 'channel_id'}
				]
			});

			this.$hasTip = ['creative_id', 'campaign_id', 'campaign_name', 'package_id'];
			this.$def = {
				'dimId': 0,
				'dimText': LANG('请选择'),
				'operatorId': 0,
				'operatorText': LANG('请选择'),
				'value': '',
				'hasLine': false,
				// 控制添加条件弹窗里面的按钮的显隐
				'showInput': true,
				// 添加条件弹窗里的按钮的值
				'buttonValue': '',
				// 选择了的活动标签或者渠道的数目
				'chooseData': [],
				// 显示的文本内容
				'countText': ''
			};

			this.Super('init', arguments);
		},
		afterBuild: function(){
			var self = this;
			self.Super('afterBuild',arguments);
			var el = self.getContainer('body');
			this.$index = 0; // 当前操作条件在conditions中的索引
			this.$buttonIndex = 0; // 当操作选择按钮
			this.$current = 1; // 当前操作菜单
			// 运算符
			this.$comparison = {}; // 运算符map
			this.$comparisonArr = []; // 运算符数组
			this.$labelData = {}; // 选择活动标签的数据
			var operators = pubjs.config('smartMonitorOperator');
			for( var i = 0; i < operators.length; i++ ) {
				this.$comparison[i] = operators[i]['_id'];
				this.$comparisonArr.push({
					'_id': i,
					'Name': operators[i]['Name']
				})
			}

			// 指数
			el.append([
				'<div class="M-addCondition mb20 uk-form">',
					'<div class="M-addConditionItem" ms-repeat-item="conditions">',
						'<div class="andLine" ms-visible="item.hasLine"><span class="text">'+ LANG('且') +'</span></div>',
						'<span class="ml10 selectBox" ms-click="clickShowMenu(this, $index, 1)">',
							'<span ms-text="item.dimText" class="ipt w120 text-truncate"></span>',
							'<span type="button" class="btn"></span>',
						'</span>',
						'<span class="ml10 selectBox" ms-click="clickShowMenu(this, $index, 2)">',
							'<span ms-text="item.operatorText" class="ipt w80 text-truncate"></span>',
							'<span type="button" class="btn"></span>',
						'</span>',
						'<input ms-visible="item.showInput" ms-duplex="item.value" type="text" class="w160 ml10">',
						'<input ms-visible="!item.showInput" ms-click="buttonClick(this, $index)" type="button" ms-value="item.buttonValue" class="w160 ml10 btn buttonBg"/>',
						'<span class="tips pl10"/>',
						'<span ms-class-1="lastAdd:$last" class="op add" ms-click="clickAdd" title="'+ LANG('增加一条') +'">+</span>',
						'<span class="op remove" ms-click="clickRemove($index)" title="'+ LANG('删除该条') +'" ms-visible="showDelBtn">×</span>',
						'<span class="ml10 countText" ms-visible="item.chooseData.length" ms-text="item.countText"></span>',
					'</div>',
				'</div>'
			].join(''));

			this.createAsync('labelList', "report/popwin/checkBoxPopwin.base", {
				'data': [],
				'title': LANG('活动标签')
			});
			this.eventAdd();
		},
		// 弹出菜单
		eventShowMenu: function( elm, index, type ) {
			var c = this.getConfig();
			var vm = this.vm.$;
			var condition = vm['conditions'][index];
			var trigger = $(elm);
			var menu = this.get('menu');
			var config = {
				'trigger': trigger,
				'relate_elm': trigger,
				'key': '_id',
				'name': 'Name',
				'offsetLeft': 1,
				'offsetTop': -10
			};
			this.$index = index; // 标记当前条件索引
			this.$current = type; // 标记当前菜单


			switch( type ) {
				// 计数维度菜单
				case 1:
					config = $.extend( true, config, {
						'options': c.dim
						//'data_set': [{
						//	'_id': condition['dimId']
						//}]
					});
				break;
				// 运算符菜单
				case 2:
					var dim = condition.dimId;
					var options;
					if(dim === 'creative_id' || dim === 'campaign_id' || dim === 'package_id')
					{
						options = c.operator && c.operator.dim;
					}
					else if(dim === 'campaign_label' || dim === 'channel_id' || dim === 'campaign_name'){
						options = c.operator && c.operator.newDim;
					}
					else
					{
						options = c.operator && c.operator.metric;
					}

					config = $.extend( true, config, {
						'options': options || []
						//'data_set': [{
						//	'_id': condition['operatorId']
						//}]
					});
				break;
			}
			if( !menu ) {
				this.createAsync('menu', '@base/common/menu.base', config);
			}
			else {
				menu.destroy();
			}
		},
		showPop: function()
		{
			var self = this;
			var mod = self.$.popCond;
			if(!mod)
			{
				this.createAsync('popCond',"modules/metricPanelPopwin.base", {
					singleSelect: true
				},function(mod) {
					mod.reset().show();
				});
			}
			else
			{
				mod.reset().show();
			}
		},
		onMetricSelect: function(ev)
		{
			var option = this.getConfig('operator/metric');
			var value = ev.param;
			var condition = this.$selectCond;
			condition.dimId = value.id;
			condition.dimText = value.name;
			condition.operatorId = option[0]._id;
			condition.operatorText = option[0].Name;
		},
		onMenuSelected: function( ev ) {
			var vm = this.vm.$;
			var param = ev.param[0];
			var id = param['key'];
			var name = param['name'];
			var condition = vm['conditions'][this.$index];
			// 设置对应菜单的值
			switch( this.$current ) {
				// 计数维度
				case 1:
					// 清除已选的活动标签或者渠道
					condition.chooseData = [];
					// 清除已填写的value值
					condition.value = '';

					if(id === 'metric')
					{
						this.$selectCond = condition;
						this.showPop();
					}
					else
					{
						if(condition.dimId != id)
						{
							var option = this.getConfig('operator/dim');
							condition.dimId = id;
							condition.dimText = name;
							condition.operatorId = option[0]._id;
							condition.operatorText = option[0].Name;
						}
					}
					// 控制input框和button的显隐
					if (id === 'campaign_label' || id === 'channel_id') {
						condition.showInput = false;
						condition.buttonValue = (id === 'campaign_label') ? '选择标签' : '选择渠道';
					}
					else {
						condition.showInput = true;
					}

					// 创建提示模块
					this.showTips(id, this.$index);

				break;
				// 运算符
				case 2:
					if(condition.operatorId != id)
					{
						condition.operatorId = id;
						condition.operatorText = name;
					}
				break;
			}


			this.get('menu').destroy();
			return false;
		},
		eventAdd: function()
		{
			var vm = this.vm.$;
			if( vm['conditions'].length >= 5 )
			{
				pubjs.alert(LANG('已达到条件的最大数量！'));
			}
			else
			{
				var def = util.clone(this.$def);
				if(vm.conditions.length)
				{
					def['hasLine'] = true;
				}

				vm['conditions'].push( def );
				vm['showDelBtn'] = vm['conditions'].length > 1;
			}
			return false;
		},
		eventRemove: function( index ) {
			var vm = this.vm.$;
			vm['conditions'].splice( index, 1 );
			if( vm['conditions'].length === 1 ) {
				vm['showDelBtn'] = false;
			}
			else {
				vm['showDelBtn'] = true;
			}
			vm['conditions'][0]['hasLine'] = false;

			this.deleteTips(index);
			return false;
		},
		// 格式化条件数组
		formatConditionArray: function( arr ) {
			var self = this;
			var vm = self.vm.$;
			var retArr = [];
			util.each(arr, function(item, i) {
				item.hasLine = i > 0;
				retArr.push(item);
			});

			vm.showDelBtn = retArr.length > 1;
			return retArr;
		},
		validate: function(data)
		{
			var self = this;
			var valid = true;
			var array_regex = /[^0-9\s,]/;
			var number_regex = /[^0-9\s]/;
			if(data && data.length)
			{
				util.each(data, function(item) {
					if (item.dimId === 'campaign_name') {
						if (!item.value) {
							pubjs.alert(`${item.value} 为空或不合规则，请重新输入`);
							valid = false;
							return false;
						}
					}
					else {
						var regex = ['campaign_id', 'creative_id', 'package_id'].indexOf(item.dimId) > -1 ? array_regex : number_regex;
						if( (!item.value || item.value.match(regex)) && !item.chooseData.length )
						{
							pubjs.alert(`${item.value} 为空或不合规则，请重新输入`);
							valid = false;
							return false;
						}
					}
				});
			}

			return valid;
		},
		setData: function(data, index)
		{
			var vm = this.vm.$;
			this.$id = index;
			vm.conditions = this.formatConditionArray(util.clone(data));
			// 设置对应的tips的显示
			for (var i = 0; i<data.length; i++) {
				var item = data[i];
				this.showTips(item.dimId, i);
			}
			return this;
		},
		getData: function() {
			var data = util.clone(this.vm.getItem('conditions'));
			if(data && data.length)
			{
				for(var i = data.length -1; i >= 0; i--)
				{
					var item = data[i];
					if(!item.dimId || !item.operatorId || (!item.value && !item.chooseData.length))
					{
						data.splice(i, 1);
					}
				}
			}

			return data;
		},
		onOk: function()
		{
			var value = this.getData();
			if(!value.length)
			{
				return pubjs.alert('请先选择相应的条件');
			}

			if(this.validate(value))
			{
				this.hide();
				this.fire('conditionSelect', {index: this.$id, value: value});
			}

			return false;
		},
		reset: function() {
			this.vm.reset();
			this.$id = null;
			this.eventAdd();
			// 删除所有创建了的tips
			this.deleteTips();
			return this;
		},
		onUserSet: function(ev)
		{
			this.$userId = ev.param && ev.param.ids;
		},
		showLabel: function(chooseIds){
			var self = this;
			var c = this.getConfig();
			// 如果有缓存，直接创建，否则拉取数据再创建
			if(!this.$userId)
			{
				pubjs.alert(LANG('请先选择用户才能获取相应的标签信息'));
				return false;
			}

			var labelData = this.$labelData[this.$userId];
			if (labelData)
			{
				this.createLabelList(labelData, chooseIds);
			}
			else
			{
				pubjs.mc.send(c.labelUrl, {AdvIds: this.$userId}, this.onShowLabel.bind(self), chooseIds);
			}
		},
		onShowLabel: function(err, data, param){
			var self = this;
			var vm = self.vm.$;
			if(err)
			{
				pubjs.alert(err.message);
				return false;
			}
			else
			{
				// 给标签的名字加上对应的数目
				for (var i = 0; i<data.items.length; i++)
				{
					var item = data.items[i];
					item.id = item.name;
					item.name = item.name + "(" + item.count + ")";
				}

				this.$labelData[this.$userId] = data.items;
				this.createLabelList(data.items, param);
			}
		},
		createLabelList: function(data, chooseIds){
			var self = this;
			var mod = self.$.labelList;
			if(mod)
			{
				mod.buildList(data);
				mod.reset().show();
				if (chooseIds)
				{
					mod.setData(chooseIds);
				}
			}
		},
		showChannel: function(chooseIds){
			var self = this;
			var vm = self.vm.$;
			var mod = self.$.channelList;
			if (!mod) {
				this.createAsync('channelList', "admin/customDownload/popwin/checkBoxPopwin.base", {
					'data': pubjs.config('exchange'),
					'title': LANG('渠道')
				}, function(mod){
					mod.reset().show();
					if (chooseIds) {
						mod.setData(chooseIds);
					}
				});
			}
			else {
				mod.reset().show();
				if (chooseIds) {
					mod.setData(chooseIds);
				}
			}
		},
		showTips: function(id, index){
			if (~this.$hasTip.indexOf(id))
			{
				var dom = this.getDOM();
				var items = dom.find('.M-addConditionItem');
				var item = $(items[index]).find('.tips');
				this.createTips(item, index);
			}
			else {
				var tipName = 'tips' + index;
				var mod = this.$[tipName];
				if (mod) {
					mod.hide();
				}
			}
			return this;
		},
		createTips: function(dom, index){
			var self = this;
			var tipName = 'tips'+ index;
			var mod = this.$[tipName];
			if (!mod) {
				this.createAsync('tips' + index, "@base/tip.desc", {
					'target': dom,
					'width': 300,
					'data': LANG('多个值用英文“,”分开。')
				});
			}
			else {
				mod.show();
			}
			return this;
		},
		/**
		 * 删除tips的容器
		 * 有参数index，表示删除单条，没有表示删除全部
		 * @param  {number} index 需要删除那条tips
		 */
		deleteTips: function(index){
			var cs = this.$;
			var tipsName = '';
			if (index) {
				tipsName = 'tips' + index;
				if (cs[tipsName]) {
						cs[tipsName].destroy();
					}
			}
			else {
				for (var i = 0; i<6; i++) {
					tipsName = 'tips' + i;
					if (cs[tipsName]) {
						cs[tipsName].destroy();
					}
				}
			}

			return this;
		},
		eventButtonClick: function(elm, index){
			var vm = this.vm.$;
			// 拿到chooseData里面的id
			var chooseIds = [];
			var data = vm['conditions'][index].chooseData;
			data.forEach(function(item){
				chooseIds.push(item.id);
			});
			// 当前点击的按钮在conditions里面的index
			this.$buttonIndex = index;
			var value = elm.value;
			switch (value){
				case '选择标签':
					this.showLabel(chooseIds);
					break;
				case '选择渠道':
					this.showChannel(chooseIds);
					break;
			}
		},
		// 选择活动标签或者渠道选择成功后
		onSaveLabel: function(ev){
			var vm = this.vm.$;
			var conditions = vm['conditions'][this.$buttonIndex];
			var chooseData = ev.param;
			conditions.chooseData = chooseData;
			var name = ev.name;
			switch (name){
				case 'labelList':
					conditions.countText = "已选择" + chooseData.length + "个活动标签";
					break;
				case 'channelList':
					conditions.countText = "已选择" + chooseData.length + "个渠道";
					break;
			}
		},
		// 选择指标弹窗点击取消后
		onMetricCancle: function(){
			var vm = this.vm.$;
			var condition = vm['conditions'][this.$index];
			var tipsName = 'tips'+ this.$index;
			var dimId = condition.dimId;
			// 取消时，tips的显隐
			if (~this.$hasTip.indexOf(dimId))
			{
				if (this.$[tipsName]) {
					this.$[tipsName].show();
				}
			}

			// 取消时，input的显隐
			if (dimId === 'campaign_label' || dimId === 'channel_id') {
				condition.showInput = false;
				condition.buttonValue = (dimId === 'campaign_label') ? '选择标签' : '选择渠道';
			}
			return this;
		}
	});

	exports.base = AddCondition;	// 根据字段获取数组相应元素
	function _getItemByFiled( arr, val, filed ) {
		for( var i = 0; i < arr.length; i++ ) {
			if( arr[i][filed] === val ) {
				return arr[i];
			}
		}
	}

	// 获取对象键值名
	function _getKeyName( val, obj ) {
		var key = '';
		if( ( !val || !obj ) ) {
			return false;
		}
		for( key in obj ) {
			if( obj[key] == val ) {
				return key;
			}
		}
	}
});